import cv2
from target import Target
import numpy as np


def redPixelFilter(img):

    # 转换为HSV格式
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # 提取红色区域
    lower_red = np.array([156, 43, 46])
    upper_red = np.array([180, 255, 255])
    mask = cv2.inRange(hsv, lower_red, upper_red)
    # 遍历替换
    for i in range(mask.shape[0]):
        for j in range(mask.shape[1]):
            if mask[i, j] == 255:
                img[i, j] = (255, 255, 255)  # 此处替换颜色，为BGR通道
            else:
                img[i, j] = (0, 0, 0)

    return img


def redFontScanner(img):
    # img膨胀操作
    kernel = np.ones((2, 2), np.uint8)
    img = cv2.dilate(img, kernel, iterations=9)

    # 将白色与黑色反转
    img = cv2.bitwise_not(img)
    # 转换为灰度图
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 将黑色的字体用红色方框标记出来
    contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    return img, contours


def getRectangleList(contours, img):
    number_of_contours = 0
    target_list = []
    for i, contour in enumerate(contours):

        # 获取矩形轮廓的边界坐标
        x, y, w, h = cv2.boundingRect(contour)

        # 根据坐标切割出矩形区域
        card = img[y:y + h, x:x + w].copy()

        # 筛选出面积大于5000的区域
        if 5000 < card.shape[0] * card.shape[1] < img.shape[0] * img.shape[1]:

            # 保存图片
            filename = 'result/' + str(i) + '.png'
            cv2.imwrite(filename, card)

            # 画出矩形
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 0), 3)

            number_of_contours += 1
            target_list.append(Target(filename, x, y, w, h))

    return target_list, number_of_contours


def obtainTestScores(target_list):
    result_number = 0

    # 遍历识别计算结果
    while len(target_list) > 0:
        # 判断是否有右边的数字
        have_right, index = target_list[0].have_right(target_list)
        if have_right:
            # 计算两个数字的和
            result_number += target_list[0].get_number() * 10 + target_list[index].get_number()

            # 移除已处理的目标
            target_list.pop(0)
            target_list.pop(index - 1)  # 注意，由于已经移除了一个元素，所以索引需要减1
        else:
            # 只有一个数字
            result_number += target_list[0].get_number()

            # 移除已处理的目标
            target_list.pop(0)

    return result_number
